// import  Vue from 'vue'
import Vuex from 'vuex'
import store from '@/vuex/store.js'
import router from '@/router/index.js'
import {createXHR} from "@/common/js/base/createXHR.js"

var server = store.state.ip+'/dynamics/publishvideo' //服务器地址
var i = '1,2';
var files = [];

//录像
function getVideo() {
	var cmr = plus.camera.getCamera();
	cmr.startVideoCapture(function(p) {
		plus.io.resolveLocalFileSystemURL(p, function(entry) {
			let src = null
			src = plus.io.convertLocalFileSystemURL(entry.toLocalURL())
			// store.commit('videoSrc', entry.toLocalURL())
			// console.log(src)
			// console.log(entry)
			store.commit('videoSrc', src)
			files.push({
				path: entry.toLocalURL(),
				name: entry.name,
				category: 'video'
			});
			router.push({
				name: 'videoRelease'
			});
		}, function(e) {
			console.log('2', e)
			// alert('读取录像文件错误：' + e.message);
		});
	}, function(e) {
		// alert('失败：' + e.message);
		console.log('1', e)
	}, {
		filename: '_doc/camera/',
		index: i
	});
}

function zip(url) {
	plus.zip.compressImage({
			src: url, //src: (String 类型 )压缩转换原始图片的路径
			dst: "_doc/upload", //压缩转换目标图片的路径
			quality: 50, //quality: (Number 类型 )压缩图片的质量.取值范围为1-100
			overwrite: true //overwrite: (Boolean 类型 )覆盖生成新文件
		},
		function(event) {
			base64(event.target)
		},
		function(error) {});
}

function getNowFormatDate() { //获取时间
	var date = new Date();
	var seperator1 = "-";
	var seperator2 = ":";
	var month = date.getMonth() + 1;
	var strDate = date.getDate();
	if(month >= 1 && month <= 9) {
		month = "0" + month;
	}
	if(strDate >= 0 && strDate <= 9) {
		strDate = "0" + strDate;
	}
	var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate +
		" " + date.getHours() + seperator2 + date.getMinutes() +
		seperator2 + date.getSeconds();
	return currentdate;
}


function upload(text) {
  var f=null;
  for(var i = 0; i < files.length; i++) {
    f = files[i];
  }
console.log('2',f);
  plus.io.resolveLocalFileSystemURL(f.path, function (entry) {
    console.log('123',entry)
    entry.file(function (file) {
      let fileReader = new plus.io.FileReader();
      fileReader.readAsDataURL(file);
      fileReader.onloadend = function (p) {
        let dataURL = p.target.result.toString();
        // return imgbase64
        console.log('q',text);
        dataURItoBlob(dataURL,text,f.name)
      }
    })
  });
};

function dataURItoBlob(base64Data,text,name) {
  console.log(text)
  var byteString;
  if (base64Data.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(base64Data.split(',')[1]);
  else
    byteString = unescape(base64Data.split(',')[1]);
  var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  let blob = new Blob([ia], {type: mimeString});
  uploads(blob,text,name)
}

function uploads(blob,text,name) {
  let p = store.state.locations;
  let province = p.province;
  let city = p.city;
  let district = p.district;
  let street = p.street;
  let streetNum = p.streetNum;
  let lat = p.lat;
  let lng = p.lng;

  var wt = plus.nativeUI.showWaiting();
  let url = null;
  var formData = new FormData();
  formData.append("userID",localStorage.userid);
  formData.append("userName",localStorage.username);
  formData.append("tags",'12');
  formData.append("permission",'1');
  formData.append("province",province);
  formData.append("city",city);
  formData.append("region",district);
  formData.append("posDetail",street + streetNum);
  formData.append("collectTime",getNowFormatDate());
  formData.append("lat",JSON.stringify(lat));
  formData.append("lng",JSON.stringify(lng));
  formData.append("contentType",'Video');
  formData.append("profile",text);
  formData.append("detail",text);
  formData.append("mp4",blob,name);
  var xhr = createXHR();
  xhr.onreadystatechange = function () {
    if((xhr.status>=200&&xhr.status<300)||xhr.status == 304){
      let msg = JSON.parse(xhr.responseText).data;
      console.log(msg)
      store.commit('videoEntry', [])
      wt.close();
      files = [];
      router.push({
        path: '/information'
      })
    }
  };
  xhr.open('POST',server, false);
  xhr.setRequestHeader("authorization", localStorage.userid + "_" + store.state.token);
  xhr.send(formData);
  return url
}



export default {
	getVideo,
	upload
}
